import 'dart:core';
import 'package:app/api/delivery-search/index.dart';
import 'package:app/components/layout/horizontal.dart';
import 'package:app/components/layout/horizontalItem.dart';
import 'package:app/components/list/index.dart';
import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import '../../components/tabFilter/TabFilterItem.dart';
import '../../components/tabFilter/index.dart';
import '../../components/appBar/index.dart';
import '../../components/group/index.dart';

class DeliverySearch extends StatefulWidget {
  const DeliverySearch({
    super.key,
  });

  @override
  State<DeliverySearch> createState() => _DeliverySearch();
}

class _DeliverySearch extends State<DeliverySearch> {

  //配送单号/拣配单号/托盘号
  String _code = "";

  List<String> _agvCode = [];

  List<String> _statusCode = [];

  List<String> _typeCode = [];

  //站点物料清单
  List<dynamic> _list = [];

  List _typeFilters = [];

  List _agvFilters = [];

  List _statusFilters = [];

  ScrollController _controller = ScrollController();

  int _page = 1;

  int _size = 3;

  late double _maxPage;

  bool _agvFlag = false;

  bool _statusFlag = false;

  bool _typeFlag = false;


  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getTabFilters();
      search();
    });
    _controller.addListener(listenerController);
  }

  void resetSearchList() {
    setState(() {
      _list = [];
      _page = 1;
    });
  }

  void listenerController() {
    if (_controller.position.pixels == _controller.position.maxScrollExtent) {
      if (_page < _maxPage) {
        setState(() {
          _page++;
        });
        search();
      }
    }
  }

  void hideKeyBorder() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  void getTabFilters() {
    DeliverySearchApi.of(context).getTabFilters().then((res) {
      setState(() {
        _typeFilters = res.data["data"]["typeList"];
        _agvFilters = res.data["data"]["agvList"];
        _statusFilters = res.data["data"]["statusList"];
      });
    });
  }

  // 设置值
  void commitValue(value) {
    resetSearchList();
    setState(() => _code = value);
    search();
  }

  void setValue(String key, String value) {
    switch (key) {
      case 'code':
        setState(() => _code = value);
        break;
      default:
        throw Exception('key error');
    }
  }

  //根据站点码查询物料清单
  void search() {
    Map<String, Object> params = {
      "code": _code,
      "agvList": _agvCode,
      "statusList": _statusCode,
      "typeList": _typeCode,
      "current": _page,
      "pageSize": _size,
      "pdaFlag": 1
    };
    DeliverySearchApi.of(context).findDeliveryList(params).then((res) {
      setState(() {
        _list.addAll(res.data['data']['rows']);
        _maxPage = res.data['data']['total'] / _size;
      });
    });
  }

  Color getBackGroundColor(code) {
    switch (code) {
      case 0 :
        return Colors.amberAccent;
      case 20 :
        return Colors.amberAccent;
      case 30 :
        return Colors.green;
      case 40 :
        return Colors.red;
      case -10 :
        return Colors.grey;
      default :
        return Colors.white;
    }
  }

  void changeFilters(Map<String, String> filter) {
    resetSearchList();
    _agvFlag = false;
    _statusFlag = false;
    _typeFlag = false;
    for (String key in filter.keys) {
      switch (key) {
        case "_agvFilters":
          _agvFlag = true;
        case "_statusFilters":
          _statusFlag = true;
        case "_typeFilters":
          _typeFlag = true;
      }
    }
    setState(() {
      _agvCode = _agvFlag ? filter['_agvFilters'].toString().split(',')  : [];
      _statusCode = _statusFlag ? filter['_statusFilters'].toString().split(',')  : [];
      _typeCode = _typeFlag ? filter['_typeFilters'].toString().split(',') : [];
    });
    search();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBars(context: context, title: '配送单查询'),
      body: GestureDetector(
        onTap: hideKeyBorder,
        child: Column(
          children: [
            Group(
              context: context,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  BrnSearchText(
                      autoFocus: false,
                      hintText: '配送单/拣配单/托盘号',
                      onTextChange: (value){
                        setValue('code', value);
                      },
                      onTextCommit: commitValue),

                ],
              ),
            ),
            TabFilter(
                item: [
                  TabFilterItem(
                      label: "车辆编号",
                      columnKey: "_agvFilters",
                      child: _agvFilters,
                      listSize: 1,
                      type: "Checkbox"),
                  TabFilterItem(
                      label: "配送类型",
                      columnKey: "_typeFilters",
                      child: _typeFilters,
                      listSize: 1,
                      type: "Checkbox"),
                  TabFilterItem(
                      label: "状态",
                      columnKey: "_statusFilters",
                      child: _statusFilters,
                      listSize: 1,
                      type: "Checkbox"),
                ],
                onSelectionChanged: (int menuIndex,
                    Map<String, String> filterParams,
                    Map<String, String> customParams,
                    BrnSetCustomSelectionMenuTitle setCustomTitleFunction,) {
                  changeFilters(filterParams);
                }),
            Expanded(
              child: ListContainer(
                controller: _controller,
                length: _list.length,
                children: (index) {
                  return [
                    Horizontal(items: [
                      HorizontalItem(
                        label: '配送单号：',
                        value: _list[index]['code'],
                      ),
                      HorizontalItem(
                        label: '状态：',
                        value: _list[index]['deliveryStatus'],
                        valueBackground:getBackGroundColor(_list[index]['status']),
                        fontColor: Colors.white,
                      )
                    ]),
                    Horizontal(items: [
                      HorizontalItem(
                        label: '拣配单号：',
                        value: _list[index]['pickCode'],
                        // valueBackground: Colors.green,
                        // fontColor: Colors.white,
                      ),
                      HorizontalItem(
                        label: '运行区域：',
                        value: _list[index]['zone'],
                      ),
                    ]),
                    Horizontal(items: [
                      HorizontalItem(
                        label: '托  盘  号：',
                        value: _list[index]['container'],
                      ),
                      HorizontalItem(
                        label: '配送类型：',
                        value: _list[index]['type'],
                      )
                    ]),
                    Horizontal(items: [
                      HorizontalItem(
                        label: '车辆编号：',
                        value: _list[index]['agv'],
                      )
                    ]),
                    Horizontal(items: [
                      HorizontalItem(
                        label: '配送起点：',
                        value: _list[index]['startStation'],
                      )
                    ]),
                    Horizontal(items: [
                      HorizontalItem(
                        label: '配送终点：',
                        value: _list[index]['endStation'],
                      ),
                    ]),
                  ];
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
